﻿using Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Net;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Tools;
using static System.Collections.Specialized.BitVector32;

namespace BLL
{
    public class SimbaBLL
    {
        private DirectoryInfo direct;
        public void SetPort(Point point, AppHelper app, string portName)
        {
            AppHelper.Delay(100);
            app.MouseClick(point);
            AppHelper.Delay(10);
            app.MouseClick(point);
            app.KeyDown(Keys.Back);
            AppHelper.Delay(20);
            app.KeyDown(Keys.Back);
            AppHelper.Delay(20);
            app.KeyDown(Keys.Back);
            Clipboard.Clear();
            Clipboard.SetText(portName);
            app.KeyDown(Keys.ControlKey, Keys.V);
        }
        public string IsPass(List<Point> points, AppHelper app)
        {
            string result = "ng";
            foreach (Point point in points)
            {
                int a = 0;
                while (app.GetPointColor(point) == ResultModel.Write && a < 10)
                {
                    AppHelper.Delay(1000);
                    a++;
                }
                Color color = app.GetPointColor(point);
                if (color == ResultModel.Fail)
                {
                    return "ng";
                }
                else if (color == ResultModel.Pass)
                {
                    result = "ok";
                }
                else
                {
                    return "ng";
                }
            }
            return result;
        }
        public string IsPass(string logder, string snimei, string station, string box, PortBLL portBLL, SerialPort port, AppHelper app, bool firstTime,string devcode)
        {
            try
            {
                string result = PortModel.NGResult;
                //string day = DateTime.Now.ToString("yyyy_MM_dd");
                //string logPath = path;
                //DirectoryInfo theFolder = new DirectoryInfo(logPath);
                //DirectoryInfo[] dirInfos = theFolder.GetDirectories();
                //theFolder = dirInfos[0];
                //foreach (var item in dirInfos)
                //{
                //    if (item.LastWriteTime > theFolder.LastWriteTime)
                //    {
                //        theFolder = item;
                //    }
                //}
                //logPath = theFolder.FullName + "\\" + station;
                //theFolder = new DirectoryInfo(logPath);
                DirectoryInfo logFolder = new DirectoryInfo(logder+ "//" + station);
                DirectoryInfo[] dirInfos = logFolder.GetDirectories();
                DateTime time1 = DateTime.Now;
                int lastCount = dirInfos.Length;
                AppHelper.Delay(25000);
                DirectoryInfo[] dirInfoend = logFolder.GetDirectories();
                bool istwo = false;
                foreach (var dir in dirInfoend)
                {

                    bool isNew = true;
                    foreach (var item in dirInfos)
                    {
                        if (item.Name == dir.Name)
                        {
                            isNew = false;
                            direct = dir;
                            break;
                        }
                    }

                    if (isNew)
                    {
                        istwo = true;
                        direct = dir;
                        break;
                    }
                }
                if (istwo&& direct.Name.Contains("_FAIL"))
                {
                    if (!Directory.Exists(logder + "\\" + station + "errRecoder"))
                    {
                        Directory.CreateDirectory(logder + "\\" + station + "errRecoder");
                    }
                    LogHelper.WriteDebugLog(direct.Name + box.Replace("测试箱", "") + "错误文件生成时间过短，可能是夹具反应不及时");
                    direct.MoveTo(logder + "\\" + station + "errRecoder" + "\\" + direct.Name);
                    return "two";
                }
                AppHelper.Delay(10000);
                while (true)
                {
                    DateTime time2 = DateTime.Now;

                    DirectoryInfo[] dirInfo = logFolder.GetDirectories();
                    if ((time2 - time1).TotalMinutes > 2)
                    {
                        
                        if (dirInfos.Length+1 == dirInfo.Length)
                        {
                            portBLL.SendData(port, PortModel.Warnning + "#" + box.Replace("测试箱", ""));
                            LogHelper.WriteDebugLog(direct.Name + box.Replace("测试箱", "") + "文件不完整");
                            if (!Directory.Exists(logder + "\\" + station + "errRecoder"))
                            {
                                Directory.CreateDirectory(logder + "\\" + station + "errRecoder");
                            }
                            
                            direct.MoveTo(logder + "\\" + station + "errRecoder" + "\\" + direct.Name);
                        }
                        else
                        {
                            result = PortModel.ZCPowerOFF;
                        }
                        return result;
                    }
                    AppHelper.Delay(1000);
                    
                    //if (dirInfo.Length == lastCount)
                    //{
                    //    continue;
                    //}
                    foreach (var dir in dirInfo)
                    {
                      
                        bool isNew = true;
                        foreach (var item in dirInfos)
                        {
                            if (item.Name == dir.Name )
                            {
                                isNew = false;
                                direct = dir;
                                break;
                            } 
                        }
                      
                        if (isNew)
                        {
                            direct = dir;
                            break;
                        }
                    }
                    if (direct.Name.Length < 27)
                    {
                        continue;
                    }
                    if (direct.Name.Contains(snimei.Split(';')[1])&& direct.Name.Contains("_PASS"))
                    {
                        result = PortModel.OKresult;
                    }
                    if(direct.Name.Contains("_PASS")|| direct.Name.Contains("_FAIL"))
                    {
                        break;
                    }
                }
                SysTestModel testModel = GetTestModel(snimei, result, devcode);
                if (testModel == null)
                {
                    result = PortModel.NGResult;
                }
                result = WriteSynTest1(testModel, direct, station, logder, result);
                return result;
            }
            catch (Exception e)
            {
                LogHelper.WriteDebugLog(e.ToString());
                return PortModel.ZCPowerOFF;
            }
        }
        public string WriteSynTest1(SysTestModel model,DirectoryInfo direct,string pth,string path, string result1)//调用综测
        {
            string result = result1;
            for (int i= 0;i<10;i++) {
                string json1 = "causelog= &createuser=" + "test" + "&devcode=" + model.devcode + "&imei=" + model.imei + "&param= &result=" + model.result + "&sn=" + model.prodsn + "&type=2";
                LogHelper.WriteLog(model.prodsn + "调用校准写入接口：" + json1);
                //string url = "http://192.168.2.23:9213/integrate/cmcc/ctAddForDevcodeNew?";
                string url = "http://192.168.2.23:9295/integrate/cmcc/ctAddForDevcodeNew?";
                string getMsg1 = Get(json1, url);
                LogHelper.WriteLog(model.prodsn + "调用校准写入接口返回值：" + getMsg1);
                if (!getMsg1.Contains("200")&&i==9)
                {
                    LogHelper.WriteDebugLog(getMsg1);
                    if (!Directory.Exists(path + "\\" + pth + "errRecoder"))
                    {
                        Directory.CreateDirectory(path + "\\" + pth + "errRecoder");
                    }
                    direct.MoveTo(path + "\\" + pth + "errRecoder" + "\\" + direct.Name);
                    result = PortModel.NGResult;
                }
                if (getMsg1.Contains("200"))
                {
                    if (!Directory.Exists(path + "\\" + pth + "Recoder"))
                    {
                        Directory.CreateDirectory(path + "\\" + pth + "Recoder");
                    }
                    direct.MoveTo(path + "\\" + pth + "Recoder" + "\\" + direct.Name);
                    break;
                }
            }
            return result;
        }
        public static string Get(string json, string url)
        {
            string username = "";
            try
            {
                url = url + json;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";
                request.ServicePoint.Expect100Continue = false;

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                string returnXml = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                username = returnXml;
            }
            catch (Exception ee)
            {

            }
            return username;
        }
        
        public void MoveLog(string logPath, DirectoryInfo[] dirInfo, FileInfo[] fileInfo)
        {
            DirectoryInfo theFolder = new DirectoryInfo(logPath);
            string movePath = logPath + "\\History";
            if (!Directory.Exists(movePath))
            {
                Directory.CreateDirectory(movePath);
            }
            //遍历文件夹
            foreach (DirectoryInfo file in dirInfo)
            {
                if (file.Name!="History")
                {
                    file.MoveTo(movePath + "\\" + file.Name);
                }
            }
            foreach (FileInfo file in fileInfo)
            {
                file.MoveTo(movePath + "\\" + file.Name);
            }
        }
        public SysTestModel GetTestModel(string snimei, string result, string devcode, string err = "")
        {
            try
            {
                SysTestModel ML302Model = new SysTestModel();
                ML302Model.prodsn = snimei.Split(';')[1];
                ML302Model.imei = snimei.Split(';')[0];
                ML302Model.result = result.Replace("Result", "").Trim().ToUpper();
                ML302Model.idproductionline = "3";
                ML302Model.devcode = devcode.Replace("测试箱", "");
                ML302Model.createuser = "自动线";
                if (err != "")
                {
                    ML302Model.causelog = err;
                }
                else if (result.Contains("Ng") && direct.Name.Contains("FAIL"))
                {
                    ML302Model.causelog = Regex.Split(direct.Name, "_FAIL")[0].Split(')')[0] + ")";
                    
                }
                return ML302Model;
            }
            catch (Exception e)
            {
                LogHelper.WriteDebugLog(e.ToString());
                return null;
            }
        }
    }
}
